package com.lhsy.djcloud.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lhsy.djcloud.common.ReturnT;
import com.lhsy.djcloud.common.SecurityConstant;
import com.lhsy.djcloud.controller.vo.MeetingVo;
import com.lhsy.djcloud.controller.vo.NoticeMessageVo;
import com.lhsy.djcloud.controller.vo.SearchVo;
import com.lhsy.djcloud.entity.*;
import com.lhsy.djcloud.entity.dto.UserDto;
import com.lhsy.djcloud.service.AdviceService;
import com.lhsy.djcloud.service.DepartmentService;
import com.lhsy.djcloud.service.EmployeeService;
import com.lhsy.djcloud.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 活动相关的表 前端控制器
 * </p>
 *
 * @author wangzw
 * @since 2020-11-05
 */
@RestController
@RequestMapping("/meeting")
@Api(value = "Server-API",tags = "三会创建接口")
public class MeetingController extends BaseController{
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private AdviceService adviceService;
    @Autowired
    private UserService userService;
    @Autowired
    private EmployeeService employeeService;
    /**
     * 会议创建
     */
    @ApiOperation(value = "创建会议")
    @RequestMapping(value = "/create",method = RequestMethod.POST)
    public ReturnT send(HttpServletRequest request, @RequestBody MeetingVo meetingVo){
        //获取当前用户
        UserDto currUser = getCurrUser(request);
        List<Integer> employeeIds = meetingVo.getEmployeeIds();
        if (CollectionUtil.isEmpty(employeeIds)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"请选择参会成员");
        }
        //创建会议内容
        Advice advice = new Advice();
        advice.setTenantId(currUser.getTenantId());
        advice.setType(1);
        advice.setSendUserId(currUser.getUserId());
        String join = StrUtil.join(",", employeeIds);
        advice.setMember(join);
        advice.setTitle(meetingVo.getTitle());
        advice.setLevel(currUser.getDepartment().getLevel());
        advice.setContent(meetingVo.getContent());
        advice.setStatus(meetingVo.getStatus());
        advice.setCreateTime(new Date());
        advice.setSubmitTime(meetingVo.getExTime());
        advice.setCreateName(currUser.getUserName());
        adviceService.save(advice);
        return ReturnT.SUCCESS;
    }

    @ApiOperation(value = "编辑")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public ReturnT edit(HttpServletRequest request, @RequestBody MeetingVo meetingVo){
        //获取当前用户
        UserDto currUser = getCurrUser(request);
        List<Integer> employeeIds = meetingVo.getEmployeeIds();
        if (CollectionUtil.isEmpty(employeeIds)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"请选择参会成员");
        }
        //验证权限
        Advice advice = adviceService.getById(meetingVo.getId());
        if (Objects.isNull(advice)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"数据不存在");
        }
        if (!advice.getSendUserId().equals(currUser.getUserId()) || Integer.valueOf(2).equals(advice.getStatus())){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"暂无权限");
        }
        advice.setTenantId(currUser.getTenantId());
        advice.setType(1);
        advice.setSendUserId(currUser.getUserId());
        String join = StrUtil.join(",", employeeIds);
        advice.setMember(join);
        advice.setTitle(meetingVo.getTitle());
        advice.setLevel(currUser.getDepartment().getLevel());
        advice.setContent(meetingVo.getContent());
        advice.setStatus(meetingVo.getStatus());
        advice.setSubmitTime(meetingVo.getExTime());
        advice.setCreateName(currUser.getUserName());
        adviceService.updateById(advice);
        return ReturnT.SUCCESS;
    }

    /**
     * 会议查询
     */
    @ApiOperation(value = "会议查询")
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public ReturnT list(HttpServletRequest request, @RequestBody SearchVo searchVo){
        //获取当前用户
        UserDto currUser = getCurrUser(request);
        searchVo.setType(1);
        searchVo.setTenantId(currUser.getTenantId());
        List<Advice> adviceList = Lists.newArrayList();
        if (currUser.getRoleName().equals(SecurityConstant.DJG_ROLE)){
            //查询所有
            PageHelper.startPage(searchVo.getPageNo(),searchVo.getPageSize());
            adviceList = adviceService.selectByModel(searchVo);
        }

        if (currUser.getRoleName().equals(SecurityConstant.DZB_ROLE)){
            //当前党支部 以及 他的党小组下的所有会议
            Integer deptId = currUser.getDepartment().getId();
            List<Department> departments = departmentService.selectByPid(deptId);
            List<Integer> deptids = departments.stream().map(Department::getId).collect(Collectors.toList());
            deptids.add(deptId);
            List<User> users = userService.selectByDeptIds(deptids);
            List<Integer> userIds = users.stream().map(User::getId).collect(Collectors.toList());
            searchVo.setUserIds(userIds);
            PageHelper.startPage(searchVo.getPageNo(),searchVo.getPageSize());
            adviceList = adviceService.selectByModel(searchVo);
        }

        if (currUser.getRoleName().equals(SecurityConstant.DXZ_ROLE)){
            //只能查看他自己的会议
            PageHelper.startPage(searchVo.getPageNo(),searchVo.getPageSize());
            List<Integer> userIds = Lists.newArrayList();
            userIds.add(currUser.getUserId());
            adviceList = adviceService.selectByModel(searchVo);
        }
        PageInfo<Advice> advicePageInfo = new PageInfo<>(adviceList);
        return ReturnT.SUCCESS(advicePageInfo);
    }

    /**
     * 会议查询
     */
    @ApiOperation(value = "查看会议")
    @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public ReturnT view(HttpServletRequest request, @PathVariable Integer id){
        //获取当前用户
        UserDto currUser = getCurrUser(request);
        Advice advice = null;
        if (currUser.getRoleName().equals(SecurityConstant.DJG_ROLE)){
            //直接查询
            advice = adviceService.getById(id);
        }

        if (currUser.getRoleName().equals(SecurityConstant.DZB_ROLE)){
            //当前党支部 以及 他的党小组下的所有会议
            Integer deptId = currUser.getDepartment().getId();
            List<Department> departments = departmentService.selectByPid(deptId);
            List<Integer> deptids = departments.stream().map(Department::getId).collect(Collectors.toList());
            deptids.add(deptId);
            List<User> users = userService.selectByDeptIds(deptids);
            List<Integer> userIds = users.stream().map(User::getId).collect(Collectors.toList());
            advice = adviceService.getById(id);
            if (!userIds.contains(advice.getSendUserId())){
                return ReturnT.FAIL(ReturnT.FAIL_CODE,"权限不足");
            }

        }

        if (currUser.getRoleName().equals(SecurityConstant.DXZ_ROLE)){
            //只能查看他自己的会议
            advice = adviceService.getById(id);
            if (!currUser.getUserId().equals(advice.getSendUserId())){
                return ReturnT.FAIL(ReturnT.FAIL_CODE,"权限不足");
            }
        }
        if (Objects.isNull(advice)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"会议不存在");
        }
        //查询员工姓名拼接
        String member = advice.getMember();
        String[] split = member.split(",");
        List<String> empIdStrs = Arrays.asList(split);
        List<Integer> empIdsLists = Lists.newArrayList();
        empIdStrs.forEach(s -> {
            empIdsLists.add(Integer.valueOf(s));
        });
        List<Employee> employees = employeeService.selectByIds(empIdsLists);
        List<String> empNames = employees.stream().map(Employee::getEmpName).collect(Collectors.toList());
        advice.setMemberStr(StrUtil.join(",",empNames));
        return ReturnT.SUCCESS(advice);
    }

    @ApiOperation(value = "删除")
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.GET)
    public ReturnT delete(HttpServletRequest request, @PathVariable Integer id){
        //获取当前用户
        UserDto currUser = getCurrUser(request);
        Advice advice = null;
        if (currUser.getRoleName().equals(SecurityConstant.DJG_ROLE)){
            //直接查询
            advice = adviceService.getById(id);
        }

        if (currUser.getRoleName().equals(SecurityConstant.DZB_ROLE)){
            //当前党支部 以及 他的党小组下的所有会议
            Integer deptId = currUser.getDepartment().getId();
            List<Department> departments = departmentService.selectByPid(deptId);
            List<Integer> deptids = departments.stream().map(Department::getId).collect(Collectors.toList());
            deptids.add(deptId);
            List<User> users = userService.selectByDeptIds(deptids);
            List<Integer> userIds = users.stream().map(User::getId).collect(Collectors.toList());
            advice = adviceService.getById(id);
            if (!userIds.contains(advice.getSendUserId())){
                return ReturnT.FAIL(ReturnT.FAIL_CODE,"权限不足");
            }

        }

        if (currUser.getRoleName().equals(SecurityConstant.DXZ_ROLE)){
            //只能查看他自己的会议
            advice = adviceService.getById(id);
            if (!currUser.getUserId().equals(advice.getSendUserId())){
                return ReturnT.FAIL(ReturnT.FAIL_CODE,"权限不足");
            }
        }
        if (Objects.isNull(advice)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"会议不存在");
        }
        adviceService.removeById(id);
        return ReturnT.SUCCESS(advice);
    }
}

